<template>
  <div class="app-container">
    <div style="width:100%;margin-bottom:21px;">
      <el-input v-model="name" clearable placeholder="请输入名称" style="width:15%;" @keyup.enter.native="handleFilter"/>
      <el-button type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button size="medium" type="info" @click="clearParams">清空</el-button>
      <div style="float:right;">
        <el-button type="primary" style="float:right;" @click="addCategory()">添加分类</el-button>
        <el-button type="success" style="margin-right: 10px" @click="addMoreClassification = true">批量导入</el-button>
      </div>
    </div>
    <tree-table :data="data" :eval-func="func" :eval-args="args" :expand-all="expandAll" border>
      <el-table-column label="ID" min-width="10">
        <template slot-scope="scope">
          <span style="color:sandybrown">{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" min-width="40">
        <template slot-scope="scope">
          <span style="color:sandybrown">{{ scope.row.label }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="40" align="center">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" @click="handleClickEdit(scope.row)">编辑</el-button>
          <el-button type="success" icon="el-icon-plus" @click="addChildren(scope.row)">添加子分类</el-button>
          <el-button v-if="scope.row.parentId === 0" type="primary" icon="el-icon-edit" @click="appointVersion(scope.row)">指定版本</el-button>
        </template>
      </el-table-column>
    </tree-table>
    <tree-dialog
      :dialog-visible="dialogVisible"
      :newform="newForm"
      @submit="handleClickSubmit"
      @deleteCategory="deleteCategory"
      @cancel="cancelDialog"
    />
    <!-- 批量添加分类 -->
    <el-dialog :visible.sync="addMoreClassification" title="批量添加" width="580px">
      <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload"/>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <span v-if="addMoreLoading">正在处理，请稍等......</span>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialog" title="指定版本" width="590px">
      <el-form ref="dataForm">
        <span v-if="versionList.length === 0" style="width:100%; text-align:center; display:inline-block;">暂无版本可选择</span>
        <el-checkbox-group v-model="versionIds">
          <el-checkbox v-for="version in versionList" :label="version.id" :key="version.id">{{ version.name }}</el-checkbox>
        </el-checkbox-group>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAppoint">取 消</el-button>
        <el-button type="primary" @click="saveAppointVersion()">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import UploadExcelComponent from '@/components/UploadExcel/index.vue'
  import treeTable from '@/components/TreeTable'
  import treeToArray from './customEval'
  import TreeDialog from './dialog'
  import {addCategory, addMoreCourseCategory, appointVersion, deleteCategory, getCategoryList, getVersionList, updateCategory} from '@/api/subject/category' // 接口
  import {getTenantId} from '@/utils/auth'

  export default {
    name: 'CustomTreeTableDemo',
    components: {treeTable, TreeDialog, UploadExcelComponent},
    data() {
      return {
        newForm: {},
        dialogVisible: false,
        switchValue: false,
        func: treeToArray,
        expandAll: false,
        data: [],
        filterData: [],
        args: [null, null, 'code'],
        addMoreClassification: false,
        addMoreLoading: false,
        dialog: false,
        versionList: [],
        categoryId: '',
        versionIds: [],
        name: ''
      }
    },
    mounted() {
      this.getData()
    },
    methods: {
      addCategory() {
        this.dialogVisible = true;
        this.newForm = {};
        this.newForm.parentId = 0
      },
      cancelDialog() {
        this.dialogVisible = false;
        this.newForm = {};
        this.getData()
      },
      handleClickEdit(row) {
        this.newForm.id = row.id;
        this.newForm.name = row.name;
        this.newForm.description = row.description;
        this.newForm.parentId = row.parentId;
        this.newForm.type = row.type;
        this.newForm.tenantId = row.tenantId;
        this.newForm.icon = row.icon;
        this.newForm.hasDelete = true;
        this.dialogVisible = true
      },
      handleClickSubmit(newForm) {
        if (newForm.id) {
          updateCategory(newForm).then(res => {
            this.$notify({
              title: '成功',
              message: '成功修改课程分类！',
              type: 'success',
              duration: 2000
            });
            this.getData()
          })
        } else {
          newForm.type = 'course';
          newForm.tenantId = getTenantId();
          addCategory(newForm).then(() => {
            this.$notify({
              title: '成功',
              message: '成功创建课程分类！',
              type: 'success',
              duration: 2000
            });
            this.getData()
          })
        }
        this.dialogVisible = false
      },
      addChildren(row) {
        this.newForm = {};
        this.dialogVisible = true;
        this.newForm.parentId = row.id
      },
      deleteCategory(form) {
        deleteCategory(form.id).then(() => {
          this.$notify({
            title: '成功',
            message: '成功删除课程分类！',
            type: 'success',
            duration: 2000
          });
          this.getData()
        }).catch(() => {
          this.$message.error('删除失败，请联系管理员！')
        });
        this.dialogVisible = false
      },
      change() {
        if (!this.expandAll) {
          this.expandAll = true
        } else {
          this.expandAll = false
        }
      },
      getData() {
        getCategoryList('course', getTenantId(), '0').then(response => {
          this.data = response.data.items;
          this.filterData = response.data.items
        });
        getVersionList(getTenantId()).then(res => {
          this.versionList = res.data.items
        })
      },
      // 上传文件
      beforeUpload(file) {
        const isLt1M = file.size / 1024 / 1024 < 1;
        if (isLt1M) {
          return true
        }
        this.$message({
          message: '请不要上传大小超过1M的文件',
          type: 'warning'
        });
        return false
      },
      handleSuccess({results, header}) {
        this.addMoreLoading = true;
        results.map(item => {
          item.categoryCode = item.category_code;
          item.categoryName = item.category_name;
          item.categoryParentCode = item.category_parent_code;
          item.tenantId = getTenantId()
        });
        addMoreCourseCategory(results).then(res => {
          this.$notify({title: '成功', message: '批量导入完成', type: 'success', duration: 2000});
          this.addMoreLoading = false;
          this.getData()
        });
        this.addMoreClassification = false
      },
      saveAppointVersion() {
        let versionIds = '';
        for (const index in this.versionIds) {
          versionIds += this.versionIds[index] + ','
        }
        versionIds = versionIds.substring(0, versionIds.length - 1);
        appointVersion(versionIds, this.categoryId).then(res => {
          this.dialog = false;
          this.$notify({title: '成功', message: '成功指定版本', type: 'success', duration: 2000});
          this.getData()
        })
      },
      appointVersion(row) {
        this.dialog = true;
        this.categoryId = row.id
      },
      cancelAppoint() {
        this.dialog = false;
        this.$refs.dataForm.resetFields()
      },
      handleFilter() {
        getCategoryList('course', getTenantId(), this.name).then(response => {
          this.data = response.data.items;
          this.filterData = response.data.items
        });
      },
      clearParams() {
        this.name = '';
        this.getData()
      },
    }
  }
</script>

<style lang="scss">
  .app-container {
    padding: 0;

    .classify-switch-label {
      margin-left: 20px;

      .el-switch__label {
        height: 36px;
        padding: 8px 20px;
        background-color: rgba(133, 207, 236, 0.452);
        border-radius: 3px;
        color: #409eff;
      }
    }
  }
</style>
